<?php

namespace App\Http\Controllers;

use App\Events\OrderPaid;
use App\Exceptions\InvalidRequestException;
use App\Models\Order;
use Carbon\Carbon;
use Endroid\QrCode\QrCode;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    /**
     * 支付宝支付
     *
     * @param Order $order
     * @param Request $request
     * @return mixed
     * @throws InvalidRequestException
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function payByAlipay(Order $order, Request $request)
    {
        $this->authorize('own', $order);
        // 订单已支付或者已关闭
        if ($order->paid_at || $order->closed) {
            throw new InvalidRequestException('订单状态不正确');
        }

        // 调用支付宝的网页支付
        return app('alipay')->web(
            [
                'out_trade_no' => $order->no,
                'total_amount' => $order->total_amount,
                'subject' => '支付 Laravel Shop 的订单'.$order->no,
            ]
        );
    }

    public function alipayReturn()
    {
        try {
            app('alipay')->verify();
        } catch (\Exception$e) {
            return view('pages.error', ['msg' => '数据不正确']);
        }

        return view('pages.success', ['msg' => '付款成功']);
    }

    public function alipayNotify()
    {
        // 校验输入参数
        $data = app('alipay')->verify();
        // 如果订单状态不是成功或者结束， 则不走后续的逻辑
        // 所有交易状态：https://docs.open.alipay.com/59/103672
        if (!in_array($data->trade_status, ['TRADE_SUCCESS', 'TRADE_FINISHED'])) {
            return app('alipay')->success();
        }
        // $data->out_trade_no 拿到订单流水号，并在数据库中查询
        $order = Order::query()->where('no', $data->out_trade_no)->first();
        // 正常来说是不可能支付了一笔不存在的订单，这个判断只是加强代码的健壮性
        if (!$order) {
            return 'fail';
        }
        // 如果这笔订单的状态已经是已支付
        if ($order->paid_at) {
            // 返回数据给支付宝
            return app('alipay')->success();
        }

        $order->update(
            [
                'paid_at' => Carbon::now(),
                'payment_method' => 'alipay',
                'payment_no' => $data->trade_no,
            ]
        );

        $this->afterPaid($order);

        return app('alipay')->success();
    }

    /**
     * 微信支付
     *
     * @param Order $order
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\Response
     * @throws InvalidRequestException
     * @throws \Illuminate\Auth\Access\AuthorizationException
     */
    public function payByWechat(Order $order, Request $request)
    {
        $this->authorize('own', $order);
        // 校验订单状态
        if ($order->padid_at || $order->closed) {
            throw new InvalidRequestException('订单状态不正确');
        }

        $wechatOrder = app('wechat_pay')->scan(
            [
                'out_trade_no' => $order->no,
                // 微信与支付宝不同，微信支付的单位是分
                'total_fee' => $order->total_amount * 100,
                'body' => '支付 Laravel Shop 的订单'.$order->no,
            ]
        );
        // 把要转换为字符串作为 QrOrder 的构造函数参数
        $qrCode = new QrCode($wechatOrder->code_url);

        // 将生成的二维码图片已字符串形式输出，并且带上相应的响应类型
        return response($qrCode->writeString(), 200, ['Content-Type' => $qrCode->getContentType()]);
    }

    /**
     * 微信支付回调
     *
     * @return string
     */
    public function wechatNotify()
    {
        // 校验回调参数是否正确
        $data = app('wechat_pay')->verify();
        // 找到对应的订单
        $order = Order::query()->where(['no' => $data->out_trade_no])->first();
        // 如果订单不存在
        if (!$order) {
            return 'fail';
        }

        // 订单已支付
        if ($order->paid_at) {
            // 告诉微信支付此订单已处理
            return app('wechat_pay')->success();
        }

        // 将订单标记为已支付
        $order->update(
            [
                'paid_at' => Carbon::now(),
                'payment_method' => 'wechat',
                'payment_no' => $data->transaction_id,
            ]
        );
        $this->afterPaid($order);

        return app('wechat_pay')->success();
    }

    public function wechatRefundNotify(Request $request)
    {
        // 给微信响应失败
        $failXml = '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>';
        $data = app('wechat_pay')->verify(null, true);

        // 没有找到响应的订单,原则上是不可能发生的，保证代码的健壮性
        if (!$order = Order::query()->where('no', $data['out_trade_no'])->first()) {
            return $failXml;
        }
        if ($data['refund_status'] === 'SUCCESS') {
            // 退款成功
            $order->update([
               'refund_status'=> Order::REFUND_STATUS_SUCCESS
            ]);
        }else{
            // 退款失败，将具体的状态存入 extra 字段，并且退款状态改成失败
            $extra = $order->extra;
            $extra['refund_failed_code'] = $data['refund_status'];
            $order->update([
               'refund_status' => Order::REFUND_STATUS_FAILED
            ]);
        }

        return app('wechat_pay')->success();
    }

    public function afterPaid($order)
    {
        return event(new OrderPaid($order));
    }
}
